/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "WebSharePlugin.h"
#include "cJSON.h"

REGISTER_PLUGIN_CLASS(WebSharePlugin)
bool WebSharePlugin::execute(const string&  action, cJSON* args, CallbackContext cbc)
{
    if(action == "share") {
         m_cbc = cbc;
        cJSON* pObj = cJSON_GetArrayItem(args, 0);
        string msg = "";
        string subject = "";
        string url = "";
        if(pObj != nullptr) {
            cJSON* pMsg = cJSON_GetObjectItem(pObj, "text");
            if(pMsg != nullptr && pMsg->type == cJSON_String) {
                msg = pMsg->valuestring;
            }
            cJSON* pSubject = cJSON_GetObjectItem(pObj, "title");
            if(pSubject != nullptr && pSubject->type == cJSON_String) {
                subject = pSubject->valuestring;
            }
            cJSON* pUrl = cJSON_GetObjectItem(pObj, "url");
            if(pUrl != nullptr && pUrl->type == cJSON_String) {
                url = pUrl->valuestring;
            }
        }
        
        cJSON* pJson = cJSON_CreateObject();
        cJSON_AddStringToObject(pJson, "message", msg.c_str());
        cJSON_AddStringToObject(pJson, "subject", subject.c_str());
        cJSON_AddStringToObject(pJson, "url", url.c_str());
        char* pStr = cJSON_Print(pJson);
        executeArkTsAsync("./SocialSharing/SocialSharing/SocialSharing", 0, pStr, "WebShare", cbc);
        free(pStr);
        cJSON_Delete(pJson);
    }
    if(action == "onArKTsResult") {
        return onArKTsResult(args);
    }
    return true;
}

bool WebSharePlugin::onArKTsResult(cJSON* args)
{
    cJSON* content = cJSON_GetObjectItem(args, "content");
    string action = "";
    if(content != NULL) {
        action = content->valuestring;
    }
    if(action == "share") {
         cJSON* json = cJSON_GetObjectItem(args, "result");
        if(json != NULL && json->type == cJSON_Array) {
            int count = cJSON_GetArraySize(json);
            if(count > 0) {
                string strResult = cJSON_GetArrayItem(json, 0)->valuestring;
                if(strResult == "true") {
                    m_cbc.success(json);
                } else {
                   PluginResult pluginResult(PluginResult::ERROR, false);
                    m_cbc.sendPluginResult(pluginResult);
                }
            }
        }
    }
    return true;
}
